/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.leadiv.cards;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;

/**
 *
 * @author pborrego
 */
public class Deck<T extends Card> {
    private Vector<T> cards;
    private Vector<T> used;

    public Deck(T cards[])
    {
        this.cards = new Vector<T>(Arrays.asList(cards));
        this.used = new Vector<T>();
    }

    public Deck(Vector<T> cards)
    {
        this.cards = cards;
        this.used = new Vector<T>();
    }
    
    public void shuffle()
    {
        int i = 0;
        int len = cards.size();
        int newPos = 0;
        T tmp;
        
        for(; i < len; i++)
        {
            newPos = (int)(Math.random() * len);
            tmp = cards.elementAt(i);
            cards.set(i, cards.elementAt(newPos));
            cards.set(newPos, tmp);
        }
    }

    public T deal() throws EmptyDeckException
    {
        T c;

        try {
            c = cards.remove(0);
            used.add(c);
        } catch(java.lang.ArrayIndexOutOfBoundsException ex) {
                throw new EmptyDeckException();
        }

        return c;
    }

    public Vector<T> deal(int amt)
    {
        Vector<T> c = new Vector<T>(amt);
        int i = 0;
        T tmp;

        for(; i < amt; i++)
        {
            tmp = cards.remove(0);
            used.add(tmp);
            c.add(tmp);
        }

        return c;
    }

    public void dealPlayers(int playercnt, T[][] players) throws EmptyDeckException
    {
        int i = 0, j = 0;
        int max = 0;

        for(; i < playercnt; i++)
        {
            max = (max < players[i].length) ? players[i].length : max;
        }

        for(; j < max; j++)
        {
            for(i=0; i < playercnt; i++)
            {
                if(players[i].length > j)
                {
                    players[i][j] = deal();
                }
            }
        }
    }

    public void addCard(T c)
    {
        cards.add(c);
    }

    public int deckCount() {
        return this.cards.size();
    }

    public void reset()
    {
        cards.addAll(used);
        this.used.clear();
        shuffle();
    }

    public void printDeck()
    {
        Iterator<T> iter = cards.iterator();

        while(iter.hasNext())
        {
            iter.next().printCard();
        }
    }
}
